package com.xiaochun.hxhj;


import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.myapp.MyApp;
import com.util.ActivityCollector;
import com.util.InfoEventMessage;
import com.util.MyLog;
import com.util.StatusBarUtil;
import com.util.SystemStatusManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Map;

import butterknife.ButterKnife;

public abstract class BaseActivity extends AppCompatActivity {
    //获取TAG的activity名称
    protected final String TAG = this.getClass().getSimpleName();
    //封装Toast对象
    public static Toast toast;
    public Context context;
    public MyApp myapp;
    public SharedPreferences.Editor edit;
    public SharedPreferences sharedPreferences;
    private TextView tv_title;
    private TextView tv_save;
    private LinearLayout ll_top;
    private PopupWindow mPopupWindowexit;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        super.setContentView(R.layout.activity_base);
        //设置布局
        MyLog.e("BaseActivity被创建","BaseActivity被创建");
        setContentView(initLayout());
        StatusBarUtil.transparencyBar(this); //设置状态栏全透明
        StatusBarUtil.StatusBarLightMode(this); //设置白底黑字
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        context = this;
        myapp = (MyApp) getApplicationContext();
        setTranslucentStatus();
        EventBus.getDefault().register(this);
        sharedPreferences = getSharedPreferences("userinfo", Activity.MODE_PRIVATE);
        edit = sharedPreferences.edit();
        //activity管理
        ActivityCollector.addActivity(this);
        ButterKnife.bind(this);
        ll_top = (LinearLayout) findViewById(R.id.ll_top);
        LinearLayout ll_reback = (LinearLayout) findViewById(R.id.ll_reback);
        tv_title = (TextView) findViewById(R.id.tv_title);
        tv_save = (TextView) findViewById(R.id.tv_save);
        ll_reback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        //初始化控件
        initView();

        //设置数据
        initData();
        initListener();
    }

    protected abstract void initListener();
    /**
     * 初始化布局
     *
     * @return 布局id
     */
    protected abstract int initLayout();

    /**
     * 初始化控件
     */
    protected abstract void initView();

    /**
     * 设置数据
     */
    protected abstract void initData();


    /**
     * 保证同一按钮在1秒内只会响应一次点击事件
     */
    public abstract class OnSingleClickListener implements View.OnClickListener {
        //两次点击按钮之间的间隔，目前为1000ms
        private static final int MIN_CLICK_DELAY_TIME = 1000;
        private long lastClickTime;

        public abstract void onSingleClick(View view);

        @Override
        public void onClick(View view) {
            long curClickTime = System.currentTimeMillis();
            if ((curClickTime - lastClickTime) >= MIN_CLICK_DELAY_TIME) {
                lastClickTime = curClickTime;
                onSingleClick(view);
            }
        }
    }

    /**
     * 同一按钮在短时间内可重复响应点击事件
     */
    public abstract class OnMultiClickListener implements View.OnClickListener {
        public abstract void onMultiClick(View view);

        @Override
        public void onClick(View v) {
            onMultiClick(v);
        }
    }

    /**
     * 显示提示  toast
     *
     * @param msg 提示信息
     */
    @SuppressLint("ShowToast")
    public void showToast(String msg) {
        try {
            if (null == toast) {
                toast = Toast.makeText(context, msg, Toast.LENGTH_SHORT);
            } else {
                toast.setText(msg);
            }
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    toast.show();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            //解决在子线程中调用Toast的异常情况处理
            Looper.prepare();
            Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
            Looper.loop();
        }
    }


    /**
     * 隐藏软键盘
     */
    public void hideSoftInput() {
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        if (getCurrentFocus() != null && null != imm) {
            imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
        }
    }

    /**
     * 显示软键盘
     */
    public void showSoftInput() {
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        if (getCurrentFocus() != null && null != imm) {
            imm.showSoftInputFromInputMethod(getCurrentFocus().getWindowToken(), 0);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //activity管理
        ActivityCollector.removeActivity(this);
    }
    /**
     * 设置状态栏背景状态
     */
    public  void setTranslucentStatus()
    {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
        {
            Window win =  getWindow();
            WindowManager.LayoutParams winParams = win.getAttributes();
            final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
            winParams.flags |= bits;
            win.setAttributes(winParams);
        }
        SystemStatusManager tintManager = new SystemStatusManager(this);
        tintManager.setStatusBarTintEnabled(true);
        tintManager.setStatusBarTintResource(0);//状态栏无背景
    }

    public void saveNoticeList(String key, String string) {
        edit.putString(key, string).commit();
    }
    /**
     *获取专家字最大最小值
     */
    public String getVoiceList(String key) {
            String json = sharedPreferences.getString(key,"");

        return json;
    }




    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();

    }
    //改变中间标题
    public void changeTitle(String title) {
        if (title != null) {
            this.tv_title.setText(title);
        }
    }
    //改变中间标题
    public void showRightView(Boolean show) {
        if (show) {
            this.tv_save.setVisibility(View.VISIBLE);
        }else{
            this.tv_save.setVisibility(View.GONE);
        }
    }
    public void hideTitleBar(){
        this.ll_top.setVisibility(View.GONE);
    }

    public void saveUserInfo(String key, String string) {
        edit.putString(key, string).commit();
    }
    /**
     * 取sharedPreferences里面的数据
     */
    public String getUserInfo(String key) {
        String json = sharedPreferences.getString(key,"");
        return json;
    }
    /**
     * 删sharedPreferences里面的某一个key
     */
    public void clearSingleKey(String key) {
        edit.remove(key).commit();
    }
    /**
     * 取出sharedPreferences里面的所有key，并根据新key取出对应的老key
     */
    public String getOneKey(String content){
        String keyname = "";
        String[] newsp = content.split("=");
        String newid = newsp[0];

        Map<String, ?> all = sharedPreferences.getAll();
        for (String key : all.keySet()){
            if (key != null) {
                if (key.contains("=")) {
                    String[] split = key.split("=");
                    String oldid = split[0];
                    if (oldid.equals(newid)) {
                        keyname = key;
                        break;
                    }
                }
            }


        }
        return keyname;
    }
    /**
     * 取出sharedPreferences里面的所有key，并根据新key拆分出来的ID取出对应的老key
     */
    public String getOneKeyForId(String content){
        String keyname = "";
        String newid = content;

        Map<String, ?> all = sharedPreferences.getAll();
        for (String key : all.keySet()){
            if (key != null){
                if (key.contains("=")){
                    String[] split = key.split("=");
                    String oldid = split[0];
                    if (oldid.equals(newid)){
                        keyname = key;
                        break;
                    }
                }
            }

        }
        return keyname;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(InfoEventMessage event) {
        String message = event.getMessage();
        //0失败   1成功




    }
    /**
     * 弹出退出页面搜索框
     */
    private void popbyexit(String str) {

        LayoutInflater layoutInflater = LayoutInflater.from(context);
        View popupWindow = layoutInflater.inflate(R.layout.popup_exit_app, null);

        TextView tv_des = popupWindow.findViewById(R.id.tv_des);
        tv_des.setText(str);
        TextView tv_sure = popupWindow.findViewById(R.id.tv_sure);
        tv_sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mPopupWindowexit.dismiss();
//                logoutUser();
                saveUserInfo("user_id", "");
                saveUserInfo("username", "");
                saveUserInfo("nickname", "");
                saveUserInfo("mobile", "");
                saveUserInfo("avatar", "");
                saveUserInfo("score", "");
                saveUserInfo("student_id", "");
                saveUserInfo("is_bind_wx", "");
                saveUserInfo("token", "");
                saveUserInfo("is_agent", "");
                saveUserInfo("vip_expire", "");
                saveUserInfo("is_vip", "");
                Intent intent = new Intent(context,LoginActivity.class);
                startActivity(intent);

            }
        });

        mPopupWindowexit = new PopupWindow(popupWindow, ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.MATCH_PARENT);
        int mPopupWindowWidth = mPopupWindowexit.getWidth();
        int mPopupWindowHeight = mPopupWindowexit.getHeight();
        // 需要设置一下此参数，点击外边可消失
        mPopupWindowexit.setBackgroundDrawable(new BitmapDrawable());
        mPopupWindowexit.setOutsideTouchable(true);
        mPopupWindowexit.setTouchable(true);
        mPopupWindowexit.setFocusable(true); // pop 显示时， 不让外部 view 响应点击事件
        //防止被底部虚拟键挡住
        mPopupWindowexit.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        if (Build.VERSION.SDK_INT >= 24) { // Android 7.x中,PopupWindow高度为match_parent时,会出现兼容性问题,需要处理兼容性
            int Screenheightth = getWindowManager().getDefaultDisplay().getHeight();
            mPopupWindowexit.showAtLocation(tv_title,
                    Gravity.BOTTOM,
                    0,
                    Screenheightth / 2);
//            Log.e("底部导航栏高度", utils.getNavigationBarHeight(context) + "    gaodu");

        } else {
            int Screenheightth = getWindowManager().getDefaultDisplay().getHeight();
            mPopupWindowexit.showAtLocation(tv_title,
                    Gravity.BOTTOM,
                    0,
                    0);
        }
        mPopupWindowexit.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {

            }
        });

    }


}
